<?php

namespace app\validate;

use app\Validate;
use app\model\Admins;

class AdminValidate extends Validate
{
    protected $rule =   [
        'nickname'  => ["require", "min:2"],
        'rid'   => ["require", "number", "notIn:0"],
        "username" => ["require", "length" => "6,12", "alphaDash", "uniqueUser:"],
        "password" => ["requirePwd:", "length" => "6,18", "alphaDash"],
        "id" => ["require", "number", "notIn:1"],
        "newPassword" => ["require", "length" => "6,18", "alphaDash"],
        "oldPassword" => ["require", "passwordVerify:"],
    ];

    protected $message  =   [
        'nickname.require' => '昵称必须',
        'nickname.min' => '昵称太短了',
        'rid.require' => '请选择角色',
        'rid.number' => '非法参数',
        'rid.notIn' => '超级管理员唯一',
        'username.require' => '用户必须',
        'username.length' => '用户必须6~12位',
        'username.alphaDash' => '只能包含字母、数字、下划线和破折号',
        'username.uniqueUser' => '用户名已存在',
        'password.requirePwd' => '密码必须',
        'password.length' => '密码必须6~18位',
        'password.alphaDash' => '只能包含字母、数字、下划线和破折号',
        'newPassword.require' => '密码必须',
        'newPassword.length' => '密码必须6~18位',
        'newPassword.alphaDash' => '只能包含字母、数字、下划线和破折号',
        'oldPassword.require' => '密码必须',
        'oldPassword.passwordVerify' => '密码错误',
    ];

    protected $scene = [
        'add'  =>  ['nickname', 'rid', 'username', 'password'],
        'edit'  =>  ['nickname', 'rid', 'username', 'password', "id"],
        'base' => ["nickname"],
        'safety' => ["oldPassword", "newPassword"],
    ];

    /**
     * 验证唯一用户 function
     *
     * @param string $value
     * @return bool
     */
    protected function uniqueUser(string $value): bool
    {
        $all = request()->all();
        $w = [["username", "=", $value]];
        if (isset($all["id"])) {
            $find = Admins::find($all["id"]);
            if ($value == $find["username"]) {
                $w[] = [["id", "<>", $find["id"]]];
            }
        }
        $Username = Admins::where($w)->find();
        if ($Username) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 自定义验证密码 function
     *
     * @param string $value
     * @return boolean
     */
    protected function requirePwd(string $value): bool
    {
        $all = request()->all();
        if (!isset($all["id"]) && $value == "") {
            return false;
        }
        return true;
    }

    /**
     * 验证密码 function
     *
     * @param string $value
     * @return boolean
     */
    protected function passwordVerify(string $value): bool
    {
        $Admin = session("Admin");
        $find = Admins::find($Admin->id);
        if (!password_verify($value, $find["password"])) {
            return false;
        }
        return true;
    }
}
